package com.zhonghan.recharge.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhonghan.common.bean.Result;
import com.zhonghan.common.utils.JiSuOrder;
import com.zhonghan.common.utils.RechargeOrderId;
import com.zhonghan.recharge.dao.ZhBusinessGascardOrderDao;
import com.zhonghan.recharge.dao.ZhBusinessUserDao;
import com.zhonghan.recharge.pojo.ZhBusinessGascardOrder;
import com.zhonghan.recharge.pojo.ZhBusinessUser;
import com.zhonghan.recharge.service.BusinessRechargeService;
import com.zhonghan.recharge.service.impl.jisu.BusinessJiSuRecharge;
import com.zhonghan.recharge.service.impl.jisu.JiSuRecharge;
import com.zhonghan.recharge.task.TaskList;

/**
 * 客户充值
 * @author Administrator
 *
 */
@Service
public class BusinessRechargeServiceImpl implements BusinessRechargeService{
	
	private Logger logger = Logger.getLogger(BusinessRechargeServiceImpl.class);

	@Autowired
	private ZhBusinessGascardOrderDao zhBusinessGascardOrderDao;
	
	@Autowired
	private ZhBusinessUserDao zhBusinessUserDao;
	
	public String businessRecharge() {
		
		
		return null;
	}
	
	public Result insertOilRechargeServiceFromGasnumber(ZhBusinessUser businessUser,String gasnumber,  String gastype,Integer money,String appkey,String appsecret){
		Result result = new Result();
		/**
		 * 1.扣除总金额
		 * 2.生成订单
		 */
		businessUser.setTotalAssets(businessUser.getTotalAssets()-money);
		int bus_num = zhBusinessUserDao.updateBusinessUserAssetsById(businessUser);
		if(bus_num >= 0) {
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			ZhBusinessGascardOrder zgo = new ZhBusinessGascardOrder();
			
			String orderId = RechargeOrderId.getOrderIdBigCustomer();
			zgo.setOrderNo(orderId);
			zgo.setBmItemId("");
			zgo.setRechargeAmount(1);
			zgo.setBmItemName("加油卡直充"+money+"元");
			zgo.setBmItemNum(1);
			zgo.setOpenid("bigCustomer");
			zgo.setGascardNo(gasnumber);
			zgo.setFillName(businessUser.getNickname());
			zgo.setTelephone(businessUser.getPhone());
			zgo.setBusinessId(businessUser.getId());
			zgo.setRechargeState("0");  // 充值状态 0 充值中，1 成功
			zgo.setSalePrice(money);   
			zgo.setOrderType("jisu");   //调用斑马订单
			zgo.setFacePrice(money);
			zgo.setOrderTime(sdf.format(new Date()));
			
			
			int rs = zhBusinessGascardOrderDao.insertNonEmptyZhBusinessGascardOrder(zgo);
			logger.info("生成本地订单："+rs);
				
			Result oil_result = BusinessJiSuRecharge.toRecharge(orderId, gasnumber, businessUser.getNickname(), businessUser.getPhone(), money,appkey,appsecret);
			/*Result oil_result = new Result();
			oil_result.setCode("0");//极速订单成功
			oil_result.setData("jisu_order");*/
			if(oil_result != null && "1".equals(oil_result.getCode())) {
				//OrderDetailInfo bmOrderInfo = (OrderDetailInfo)oil_result.getData();
				
				result.setCode("1");
				result.setMsg("油卡充值成功!");
				/**
				 * 更改订单状态为充值中， 获取 极速订单号
				 */
				//更改订单状态
				JiSuOrder data = (JiSuOrder)oil_result.getData();
				zhBusinessGascardOrderDao.updateRechargeStateByOrderNo(orderId, "0","",data.getOrderno());
				logger.info("订单"+orderId+"生成成功");
				result.setData(zgo.getOrderNo());
				TaskList.Business_TASK.add(businessUser.getId().toString()+","+data.getOrderno()+","+orderId+","+appkey);
				
				return result;
			}else {
				logger.info("获取极速订单失败..................");
				
				logger.info("orderId"+orderId+",");
				/**
				 * 更改订单状态
				 */
				int num = zhBusinessGascardOrderDao.updateRechargeStateByOrderNo(orderId, "9","","");
				if(num >=0) {
					//退回金额
					businessUser.setTotalAssets(businessUser.getTotalAssets()+money);
					zhBusinessUserDao.updateBusinessUserAssetsById(businessUser);
					logger.info("订单失败，退回金额"+money);
				}
				
				logger.info("油卡充值失败，订单更改完成.............."+num);
				result.setCode("0");
				result.setData(gasnumber);
				result.setMsg("油卡充值失败!");
				
			}
		}else {
			result.setCode("0");
			result.setData(gasnumber);
			result.setMsg("金额扣除失败!");
		}
				
		return result;
	}
	
	
	public Result changeMyOrderRechargeStatus(String userId,String jisuOrderid,String outOrderId,String appkey) {
		/**
		 * 先去极速查询，
		 * 然后如果状态被改变，修改系统订单状态  充值状态 0充值中 1充值成功 2充值失败 即时返回0
		 * 
		 */
		
		Result result = new Result();
		
		JiSuOrder orderDetail = BusinessJiSuRecharge.getJiSuOrderDetail(jisuOrderid,outOrderId,appkey); //(orderno, outorderno);
		if(orderDetail != null) {
			logger.info("当前订单号"+orderDetail.getOutorderno()+" 状态为"+orderDetail.getRechargestatus());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(orderDetail.getRechargestatus() ==1) {
				//订单成功
				zhBusinessGascardOrderDao.updateRechargeStateByOrderNoAndBmBillId(outOrderId, "1",sdf.format(new Date()),jisuOrderid);
				
				result.setCode("1");
				result.setData(jisuOrderid);
			}else if(orderDetail.getRechargestatus() ==2) {
				//订单失败
				int num = zhBusinessGascardOrderDao.updateRechargeStateByOrderNoAndBmBillId(outOrderId, "9",sdf.format(new Date()),jisuOrderid);
				if(num >= 0) {
					//订单失败，退款 到客户资金
					logger.info("充值失败，退款到用户："+userId+","+outOrderId+",退款金额为："+orderDetail.getTotalFee());
					ZhBusinessUser user = new ZhBusinessUser();
					user.setId(Long.valueOf(userId));
					ZhBusinessUser businessUser = zhBusinessUserDao.selectZhBusinessUserById(Long.valueOf(userId));
					
					businessUser.setTotalAssets(businessUser.getTotalAssets()+Long.valueOf(orderDetail.getAmount()));   //Amount 充值金额
					int userMoneyBack = zhBusinessUserDao.updateBusinessUserAssetsById(businessUser);
					logger.info("金额退款成功，"+userMoneyBack);
				}
				
				result.setCode("1");
			}
		}
		
		
		return result;
		
	}
	
	
	
}
